<template>
  <h2 v-if="title" class="text-xl font-semibold mb-4">{{ title }}</h2>
  <div class="app-container">
    <!-- 参数输入区域 -->
    <div class="input-section">
      <div class="url-input">
        <label>当前APP: {{ queryName }}</label>
        <!-- <input 
          v-model="requestConfig.url" 
          placeholder=""
          @input="validateUrl"
        > -->
        <span v-if="urlError" class="error">{{ urlError }}</span>
      </div>

      <div class="params-section">
        <div v-for="(param, index) in requestConfig.params" :key="index" class="param-row">
          <input v-model="param.key" placeholder="参数名" class="param-key" disabled>
          <span>=</span>
          <input v-model="param.value" placeholder="参数值" class="param-value" disabled>
          <!-- <button @click="removeParam(index)" class="remove-btn">×</button> -->
        </div>
        <!-- <button @click="addParam" class="add-btn">+ 添加参数</button> -->
      </div>
      <!-- 操作按钮 -->
      <div class="action-buttons">
        <button @click="sendRequest" :disabled="!isValid" class="send-btn">
          发送请求
        </button>
        <!-- <button @click="resetForm" class="reset-btn">重置</button> -->
      </div>
    </div>
    <!-- 结果展示 -->
    <div v-if="responseData" class="result-section">
      <h3>请求结果</h3>
      <!-- <div class="result-meta">
        <div class="meta-item">
          <span class="meta-label">状态码:</span>
          <span class="meta-value">{{ responseStatus }}</span>
        </div>
        <div class="meta-item">
          <span class="meta-label">请求URL:</span>
          <span class="meta-value">{{ fullRequestUrl }}</span>
        </div>
      </div>
      
      <div class="result-content">
        <pre>{{ formattedResponse }}</pre>
      </div> -->
      <div class="dynamic-table-container">
        <el-table :data="tableData" border highlight-current-row style="width: 100%" @sort-change="handleSortChange">
          <el-table-column v-for="column in dynamicColumns" :key="column.prop" :prop="column.prop" :label="column.label"
            :sortable="column.sortable" :filters="column.filters" :filter-method="handleFilter" />
        </el-table>
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :total="totalItems"
          layout="total, sizes, prev, pager, next, jumper" />
      </div>
    </div>
    <div v-else class="result-section">
      <h3>请求结果</h3>
      <p>{{ error }}</p>
    </div>
  </div>

</template>

<script setup>
import { defineProps, ref, computed, watch, onMounted } from 'vue'

const props = defineProps({
  title: {
    type: String,
    default: '查询信息'
  },
  // 请求对应的APP名称
  queryName: {
    type: String,
    default: '无'
  },
  // 请求地址
  // v-bind对应app.vue里面的值传递过来
  // 通过watch()监听prop更新,将值同步更新
  queryUrl: {
    type: String,
    default: ''
  },
  // 请求参数
  initialParams: {
    type: Array,
    default: () => []
  },
  // 填入请求参数的值,对应案件管理中的线索值
  // 对应的Value中只允许填入线索值
  caseClue: {
    type: String,
    default: ''
  }
})
// 请求配置
const requestConfig = ref({
  url: props.queryUrl,
  params: props.initialParams.length > 0
    ? props.initialParams.map(p => ({ ...p }))
    : [{ key: '', value: '' }]
})

// 响应数据
const responseData = ref(null)
const responseStatus = ref(null)
const error = ref(null)
const urlError = ref('')

// 验证必填项,计算属性
// url,KV都不能为空
const isValid = computed(() => {
  return requestConfig.value.url &&
    !urlError.value &&
    requestConfig.value.params.every(p => p.key) &&
    requestConfig.value.params.every(p => p.value)
})

// get请求url全路径展示
// const fullRequestUrl = computed(() => {
//   if (!requestConfig.value.url) return ''

//   const baseUrl = requestConfig.value.url.split('?')[0]
//   const params = new URLSearchParams()

//   requestConfig.value.params.forEach(param => {
//     if (param.key && param.value !== undefined) {
//       params.append(param.key, param.value)
//     }
//   })

//   return params.toString() 
//     ? `${baseUrl}?${params.toString()}`
//     : baseUrl
// })

// const formattedResponse = computed(() => {
//   try {
//     // 将responseData进行json序列化,替换值为null即不替换任何,缩进2字符
//     return JSON.stringify(responseData.value, null, 2)
//   } catch {
//     return responseData.value
//   }
// })

// 方法
// 数据校验
const validateUrl = () => {
  try {
    if (!requestConfig.value.url) {
      urlError.value = ''
      return
    }

    new URL(requestConfig.value.url)
    urlError.value = ''
  } catch {
    urlError.value = '请输入有效的URL格式'
  }
}

// 添加参数
// const addParam = () => {
//   // 对requestConfig进行添加一组KV结构的数据，实现增加一行的功能
//   requestConfig.value.params.push({ key: '', value: '' })
// }

// 删除参数
// const removeParam = (index) => {
//   if (requestConfig.value.params.length > 1) {
//     // 根据当前下标，对requestConfig进行截取，实现删除一行的功能
//     requestConfig.value.params.splice(index, 1)
//   }
// }

// 重置请求参数
// const resetForm = () => {
//   requestConfig.value = {
//     url: props.queryUrl,
//     // 判断params的值，如果KV结构大于1个，则对应的展示
//     params: props.initialParams.length > 0 
//       ? props.initialParams.map(p => ({ ...p }))
//       // 否则展示一组KV结构的空数据
//       : [{ key: '', value: '' }]
//   }
//   // 相关参数清空
//   responseData.value = null
//   responseStatus.value = null
//   error.value = null
// }

// 发起后台请求，根据url以及参数，获取返回结果
const sendRequest = async () => {
  if (!isValid.value) return
  try {
    error.value = null
    // 处理请求参数
    const params = new URLSearchParams()
    // 取requestConfig中params的值，for循环放入到请求体中去
    requestConfig.value.params.forEach(param => {
      if (param.key && param.value !== undefined) {
        // todo:组成post请求参数格式
        params.append(param.key, param.value)
      }
    })
    // 执行异步请求
    // URL处理
    // const url = params.toString() 
    //   ? `${requestConfig.value.url.split('?')[0]}?${params.toString()}`
    //   : requestConfig.value.url.split('?')[0]
    // 获得返回结果
    // const response = await fetch(url, {
    //   method: 'POST',
    //   headers: {
    //     'Content-Type': 'application/json', // 设置请求头为 JSON 格式
    //   },
    //   body: JSON.stringify(params) // 将数据转换为 JSON 字符串
    // })
    // 模拟response返回,定义好格式,最好是后端处理过结果结构
    const response = {
      status: 200,
      data: [
        { 'ceco': '430', 'tel': '153' },
        { 'ceco': '430', 'tel': '155' }
      ]
    }
    // [{ceco:"430",tel:"153"},{ceco:"430",tel:"155"}]
    responseStatus.value = response.status
    // 判断返回状态
    // if (!response.ok) {
    //   throw new Error(`请求失败: ${response.statusText}`)
    // }
    // 取返回结果值，存起来，做展示
    // const data = await response.json()
    // 对应div中的vif判断responseData，有值就做展示
    const data = response.data
    responseData.value = data
    // 将返回结果传入表格中,即tableData的值
    tableData.value = data
    totalItems.value = data.length
  } catch (err) {
    error.value = err.message
    responseData.value = null
  }
}

const queryData = [
  { ceco: "430", tel: "153", status: "active" },
  { ceco: "430", tel: "155", status: "inactive" },
  { ceco: "520", tel: "186", status: "active" }
]
const tableData = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const totalItems = ref(0)

// 动态生成表头配置
const dynamicColumns = computed(() => {
  if (tableData.value.length === 0) return []
  // 解析第一行结果就可以拿到表头(字段名)
  return Object.keys(tableData.value[0]).map(key => {
    const column = {
      prop: key,
      label: key.toUpperCase(),
      sortable: true
    }
    // 为特定字段添加筛选选项
    // if (key === 'status') {
    //   column.filters = [
    //     { text: 'Active', value: 'active' },
    //     { text: 'Inactive', value: 'inactive' }
    //   ]
    // }
    return column
  })
})

// 处理排序
const handleSortChange = ({ prop, order }) => {
  tableData.value.sort((a, b) => {
    if (order === 'ascending') {
      return a[prop] > b[prop] ? 1 : -1
    } else {
      return a[prop] < b[prop] ? 1 : -1
    }
  })
}

// 处理筛选
const handleFilter = (value, row, column) => {
  const property = column.property
  return row[property] === value
}
// 模拟API请求
// const fetchData = async () => {
//   // 实际项目中替换为axios请求
//   return new Promise(resolve => {
//     setTimeout(() => resolve(queryData), 500)
//   })
// }
// 初始化数据
onMounted(() => {
  // const data = await fetchData()
  tableData.value = queryData
  totalItems.value = queryData.length
})

// 监听props变化
watch(() => props.queryUrl, (newVal) => {
  requestConfig.value.url = newVal
  // 当请求地址变化以后，刷新表格展示为空表
  validateUrl()
})
watch(() => props.initialParams, (newVal) => {
  requestConfig.value.params = newVal.length > 0
    ? newVal.map(p => ({ ...p }))
    : [{ key: '', value: '' }]
}, { deep: true })

</script>

<style scoped>
.app-container {
  /* max-width: 800px; */
  /* margin: 0 auto; */
  padding: 20px;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  background: #f9f9f9;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  width: 100%;
  max-width: 95%;
  display: grid;
  /* 启用Grid布局 */
  grid-template-columns: 40% 60%;
  /* 定义两列的宽度比例 */
  column-gap: 5%;
  /* 设置列之间的间隔 */
  padding-left: 1%;
  padding-right: 5%;
  margin: 0 auto;
}

.input-section {
  margin-bottom: 20px;
}

.url-input {
  margin-bottom: 15px;
}

.url-input label {
  display: block;
  margin-bottom: 5px;
  font-weight: 600;
  color: #333;
}

.url-input input {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.error {
  color: #e74c3c;
  font-size: 12px;
  margin-top: 5px;
  display: block;
}

.params-section {
  border: 1px solid #eee;
  border-radius: 4px;
  padding: 10px;
  background: #fff;
}

.param-row {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  gap: 10px;
}

.param-row input {
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  flex: 1;
}

.param-key {
  min-width: 100px;
}

.param-value {
  flex: 2;
}

.remove-btn {
  background: #e74c3c;
  color: white;
  border: none;
  width: 24px;
  height: 24px;
  border-radius: 50%;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
}

.add-btn {
  background: #3498db;
  color: white;
  border: none;
  padding: 8px 12px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.action-buttons {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

.send-btn {
  background: #2ecc71;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 4px;
  cursor: pointer;
  font-weight: 600;
}

.send-btn:disabled {
  background: #95a5a6;
  cursor: not-allowed;
}

.reset-btn {
  background: #e67e22;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 4px;
  cursor: pointer;
}

.result-section {
  /* margin-top: 20px;
  padding: 15px;
  background: #fff;
  border-radius: 4px;
  border: 1px solid #eee; */
  width: 90%;
  margin-top: 20px;
  padding: 15px;
  background: #fdecea;
  border-radius: 4px;
  border: 1px solid #f5c6cb;
  color: #721c24;
}

.result-section h3 {
  margin-top: 0;
  color: #2c3e50;
}

.result-meta {
  display: flex;
  gap: 20px;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.meta-item {
  display: flex;
  gap: 5px;
}

.meta-label {
  font-weight: 600;
}

.meta-value {
  color: #3498db;
}

.result-content {
  max-height: 300px;
  overflow-y: auto;
  background: #f8f8f8;
  padding: 10px;
  border-radius: 4px;
}

.result-content pre {
  margin: 0;
  white-space: pre-wrap;
  word-wrap: break-word;
  font-family: 'Courier New', Courier, monospace;
  font-size: 13px;
}

.error-section {
  margin-top: 20px;
  padding: 15px;
  background: #fdecea;
  border-radius: 4px;
  border: 1px solid #f5c6cb;
  color: #721c24;
}

.error-section h3 {
  margin-top: 0;
}

.dynamic-table-container {
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

:deep(.el-table) {
  margin-bottom: 20px;
}

:deep(.el-table__header th) {
  background-color: #f5f7fa;
}
</style>
